import { defineStore } from 'pinia'
import http from '@/utils/uc-http'
import { http as envhttps } from '@/utils/env-http'
import logo from '@/assets/logo/logo.png'
import logo99 from '@/assets/logo/logo99.png'
import logox from '@/assets/logo/logox.png'
import loginlogo from '@/assets/login/logo.png'
import loginlogo99 from '@/assets/login/logo99.png'
import loginlogox from '@/assets/login/logox.png'

const TOKEN_KEY = 'token'

export const useUserStore = defineStore('user', () => {
  const user = ref(JSON.parse(localStorage.user || '{}'))
  const token = ref(localStorage[TOKEN_KEY])
  const route = useRoute()
  const router = useRouter()
  const showerrordialog = ref(false)
  const userInfo = ref(null)
  const packageJs = ref({})
  const logostyletype = ref(1)
  const onelogin = ref(0)
  const IPList = ref([])
  const activeIp = ref('')
  const wsenv = ref('')

  // 判断是否登录
  const checkLogin = (isGoLogin = true) => {
    token.value = localStorage[TOKEN_KEY]


    if (token.value) {
      if (!window.location.href.includes('sell')) {
        if (onelogin.value == 0) {
          router.replace({
            path: '/ticket',
          })
        }
      }

      onelogin.value = 1

      if (packageJs.value.plantcode == undefined) {
        setTimeout(() => {
          checkInfo()
        }, 500);
      }
      return true
    } else {
      if (isGoLogin) logout(true)
      return false
    }
    // return true
  }

  // 跳转登录页面
  function goLogin(isRedirect = true) {
    const query = {}

    // 登录成功自动返回
    if (isRedirect) query.redirect = encodeURIComponent(location.pathname + location.search) // NOTE 这里用的location，route.path可以被拦截跳转

    router.replace({
      path: '/login',
      query,
    })

    // location.href = location.href.split('#/')[0] + '/#/login'
  }

  // 登录成功
  const loginSuccess = async options => {
    user.value = options
    token.value = options.accessToken

    localStorage.user = JSON.stringify(options)


    localStorage.ql_admin_gid = options.gid
    localStorage.ql_admin_gname = options.gname
    localStorage.ql_admin_roles = options.username
    localStorage[TOKEN_KEY] = token.value
    localStorage.ql_admin_uid = options.uid


    router.replace({
      path: '/ticket',
    })
  }



  // 获取用户信息
  const getUserInfo = () => {
    return Promise.resolve()
    // return getUserInfoApi().then(res => {
    //   userInfo.value = res.data
    //   return res.data
    // })
  }

  // 退出
  const logout = isRedirect => {
    // localStorage.clear()
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem('user')

    user.value = null
    userInfo.value = null
    token.value = null

    goLogin(isRedirect)
  }

  const openerrordialog = () => {
    showerrordialog.value = true
  }

  const savepackageJs = (packagejs) => {
    packageJs.value = packagejs
    getIps()
  }

  const logoimg = () => {
    let productname = packageJs.value.productName
    let logoimg
    switch (productname) {
      case '风筝体育':
        logoimg = logo
        logostyletype.value = 1
        break
      case 'IB智投':
        logoimg = logo99
        logostyletype.value = 2
        break
      case 'Orange':
        logoimg = logox
        logostyletype.value = 3
        break
      default:
        break
    }
    return logoimg
  }

  const loginlogoimg = () => {
    let productname = packageJs.value.productName
    let logoimg
    console.log(productname);

    switch (productname) {
      case '风筝体育':
        logoimg = loginlogo
        logostyletype.value = 1
        break
      case 'IB智投':
        logoimg = loginlogo99
        logostyletype.value = 2
        break
      case 'Orange':
        logoimg = loginlogox
        logostyletype.value = 3
        break
      default:
        break
    }
    return logoimg
  }
  

  // 判断账号是否有效
  const checkInfo = async () => {

    if (!token.value) return
    let mac = await window.electron.getMacAddress();


    if (packageJs.value.plantcode) {

      http.post('/user_check', {
        token: token.value,
        plant_code: `${packageJs.value.plantcode}`,
        mac: mac,
      }).then((res) => {
        user.value = res


        localStorage.user = JSON.stringify(res)
        localStorage.ql_admin_gid = res.gid
        localStorage.ql_admin_gname = res.gname
        localStorage.ql_admin_roles = res.username
        localStorage.ql_admin_uid = res.uid
      })
    }
  }
  setInterval(checkInfo, 30 * 1000)

  // 获取ip列表
  const getIps = () => {
    let plantcode = packageJs.value.plantcode
    let plant
    switch (plantcode) {
      case 'auto_bet_99':
        plant = 'auto_bet:ib'
        break
      case 'auto_bet_fz':
        plant = 'auto_bet:fz'
        break
      case 'auto_bet_x':
        plant = 'auto_bet:x'
        break
      default:
        break
    }
    let body = {
      plant_code: plant
    }
    envhttps.post('/env', body).then(res => {
      let data = JSON.parse(JSON.stringify(res))
      const cachedNetwork = localStorage.getItem('selectedNetwork');
      if (cachedNetwork) {
        const networkInfo = JSON.parse(cachedNetwork);
        activeIp.value = networkInfo.name;
        wsenv.value = networkInfo.api.ws
      } else {
        const defaultNetwork = data.find(item => item.default === 1);
        if (defaultNetwork) {
          activeIp.value = defaultNetwork.name;

          const networkInfo = {
            line_code: defaultNetwork.line_code,
            name: defaultNetwork.name,
            api: defaultNetwork.api
          };
          wsenv.value = defaultNetwork.api.ws != null ? defaultNetwork.api.ws : 'ws.api.ib-bet.com'
          localStorage.setItem('selectedNetwork', JSON.stringify(networkInfo));
        }
      }

      // 遍历并设置每个网络的 speed
      data.forEach(item => {
        item.speed = -1;
      });

      IPList.value = data
      setTimeout(() => {
        window.electron.openlistentcp(JSON.stringify(IPList.value))
      }, 1000);
    })


    window.electron.ipSpeed((event, msg) => {
      IPList.value = msg
    })

  }
  // getIps()

  return {
    user,
    userInfo,
    token,
    showerrordialog,
    packageJs,
    logostyletype,
    IPList,
    activeIp,
    wsenv,

    checkLogin,
    loginSuccess,
    goLogin,
    getUserInfo,
    logout,
    openerrordialog,
    savepackageJs,
    logoimg,
    checkInfo,
    loginlogoimg,
    getIps
  }
})
